package com.myproject.myblogserver.controller;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myproject.myblogserver.contant.CommonConstants;
import com.myproject.myblogserver.dto.PageResultDto;
import com.myproject.myblogserver.dto.commentlike.CommentLikeAddDto;
import com.myproject.myblogserver.dto.commentlike.CommentLikePreviewDto;
import com.myproject.myblogserver.entity.Blog;
import com.myproject.myblogserver.entity.BlogComment;
import com.myproject.myblogserver.entity.CommentLike;
import com.myproject.myblogserver.service.IBlogCommentService;
import com.myproject.myblogserver.service.IBlogService;
import com.myproject.myblogserver.service.ICommentLikeService;
import com.myproject.myblogserver.utils.JwtUtil;

/**
 * <p>
 * 评论点赞表 前端控制器
 * </p>
 *
 * @author jiangweike
 * @since 2025-02-25
 */
@Controller
@RequestMapping("/commentLike")
public class CommentLikeController {

    @Autowired
    private ICommentLikeService commentLikeService;

    @Autowired
    private IBlogCommentService blogCommentService;

    @Autowired
    private IBlogService blogService;

    @PostMapping("/add")
    public ResponseEntity<?> add(@RequestBody CommentLikeAddDto commentLikeAddDto,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 检查评论是否存在
            var comment = blogCommentService.lambdaQuery()
                    .eq(BlogComment::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(BlogComment::getId, commentLikeAddDto.getCommentId())
                    .one();

            if (comment == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("评论不存在！");
            }

            // 检查是否已经点赞
            var existingLike = commentLikeService.lambdaQuery()
                    .eq(CommentLike::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(CommentLike::getCommentId, commentLikeAddDto.getCommentId())
                    .eq(CommentLike::getUserId, userId)
                    .one();

            if (existingLike != null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("已经点赞过了！");
            }

            // 创建新的点赞记录
            var commentLike = new CommentLike();
            commentLike.setCommentId(commentLikeAddDto.getCommentId());
            commentLike.setUserId(userId);
            commentLikeService.save(commentLike);

            return ResponseEntity.ok("点赞成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("点赞失败！");
        }
    }

    @PostMapping("/delete/{commentId}")
    public ResponseEntity<?> delete(@PathVariable Long commentId,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);
            var commentLike = commentLikeService.lambdaQuery()
                    .eq(CommentLike::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(CommentLike::getCommentId, commentId)
                    .select(CommentLike::getUserId)
                    .one();

            if (commentLike != null && userId.equals(commentLike.getUserId())) {
                commentLikeService.lambdaUpdate()
                        .set(CommentLike::getIsDeleted, CommonConstants.DELETED_STATUS_YES)
                        .eq(CommentLike::getCommentId, commentId)
                        .update();
            } else {
                throw new RuntimeException("无权取消点赞或点赞记录不存在");
            }
            return ResponseEntity.ok("取消点赞成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("取消点赞失败！"+e.getMessage());
        }
    }

    @GetMapping("get/{pageIndex}")
    public ResponseEntity<?> get(@PathVariable Integer pageIndex,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 获取用户的点赞列表
            var commentLikes = commentLikeService.lambdaQuery()
                    .eq(CommentLike::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(CommentLike::getUserId, userId)
                    .select(CommentLike::getId, CommentLike::getCommentId, CommentLike::getCreatedAt)
                    .list();

            // 获取评论ID列表
            var commentIds = commentLikes.stream().map(CommentLike::getCommentId).toList();

            // 获取评论信息
            var comments = blogCommentService.lambdaQuery()
                    .eq(BlogComment::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .in(BlogComment::getId, commentIds)
                    .select(BlogComment::getId, BlogComment::getContent, BlogComment::getBlogId)
                    .list();

            // 获取博客ID列表
            var blogIds = comments.stream().map(BlogComment::getBlogId).toList();

            // 获取博客信息
            var blogPage = blogService.lambdaQuery()
                    .eq(Blog::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .in(Blog::getId, blogIds)
                    .select(Blog::getId, Blog::getTitle, Blog::getSummary)
                    .page(new Page<>(pageIndex, CommonConstants.DEFAULT_PAGE_SIZE));

            var likePreviewList = new ArrayList<CommentLikePreviewDto>();

            // 创建映射关系
            var commentMap = comments.stream()
                    .collect(java.util.stream.Collectors.toMap(BlogComment::getId, comment -> comment));
            var blogMap = blogPage.getRecords().stream()
                    .collect(java.util.stream.Collectors.toMap(Blog::getId, blog -> blog));

            // 组装预览数据
            for (var like : commentLikes) {
                var comment = commentMap.get(like.getCommentId());
                if (comment != null) {
                    var blog = blogMap.get(comment.getBlogId());
                    if (blog != null) {
                        var preview = new CommentLikePreviewDto();
                        preview.setId(blog.getId());
                        preview.setComment(comment.getContent());
                        preview.setBlogTitle(blog.getTitle());
                        preview.setBlogSummary(blog.getSummary());
                        preview.setCreatedAt(like.getCreatedAt());
                        likePreviewList.add(preview);
                    }
                }
            }

            // 构建分页结果
            var pageResult = new PageResultDto<CommentLikePreviewDto>();
            pageResult.setContent(likePreviewList);
            pageResult.setTotalPages(blogPage.getPages());

            return ResponseEntity.ok(pageResult);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("获取点赞列表失败！");
        }
    }
}
